import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { GetLoginApi, GetLoginInfoApi } from "@/api/acl/login";
import { staticRoutes } from "@/router/routes";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    // 放在内存里面----> 保证速度
    token: getToken() as string,
    name: "",
    avatar: "",
    routes: [],
    buttons: [],
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      // 这里的token既要存在localStorage中，也要存在内存中
      const { token } = await GetLoginApi(username, password);
      setToken(token); // 存在localStorage
      this.token = token; // 除了登录页面其他的都需要token
    },
    // 获取用户数据
    async getInfo() {
      const result = await GetLoginInfoApi();
      this.name = result.name;
      this.avatar = result.avatar;
      this.routes = result.routes;
      this.buttons = result.buttons;
      this.menuRoutes = staticRoutes;
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      this.routes = [];
      this.buttons = [];
      this.menuRoutes = [];
    },
  },
});
